<template>
  <div>
    <!-- 搜索框 -->
    <van-search
      v-model.trim="value"
      shape="round"
      placeholder="请输入搜索关键词"
      @click="onInput"
    />

    <!-- 热门搜索 -->
    <div class="hotSearch" v-if="!searchList.length">
      <p class="hotTags">热门搜索</p>
      <span v-for="item in hotSearch" :key="item.first" @click="onClick(item.first)">{{ item.first }}</span>
    </div>

    <!-- 搜索结果 -->
    <div class="searchRes" v-else>
      <p class="matching">最佳匹配</p>

      <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      @load="onLoad"
      >
        <MusicItem
        :name="item.name"
        :authorName="item.ar[0].name + ' - ' + item.name"
        :id="item.id"
        v-for="(item, index) in searchList"
        :key="index"/>
      </van-list>
    </div>
  </div>

</template>

<script>
import { getHotSearch, getSearchRes } from '@/api/search.js'
import MusicItem from '@/components/MusicItem.vue'

export default {
  name: 'Search',

  data () {
    return {
      value: '',
      hotSearch: [],
      searchList: [],
      list: [],
      loading: false,
      finished: false,
      offset: 0,
      page: 28
    }
  },

  created () {
    this.getHotMusicList()
  },

  methods: {
    // 加载热门搜索
    async getHotMusicList () {
      const res = await getHotSearch()
      // console.log(res)
      this.hotSearch = res.data.result.hots
    },
    async onClick (name) {
      this.value = name
      // 获取搜索结果
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10
      })
      this.searchList = res.data.result.songs
    },
    // 搜索框变化
    onInput () {
      this.page = 1
      if (this.value === '') {
        this.searchList = []
        clearTimeout(this.id)
        return
      }
      if (this.id) {
        clearTimeout(this.id)
      }
      this.id = setTimeout(async () => {
        const res = await getSearchRes({
          keywords: this.value,
          limit: 10
        })
        this.searchList = res.data.result.songs
      }, 800)
    },
    async onLoad () {
      this.page++
      console.log('触发onload')
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      const res = await getSearchRes({
        keywords: this.value,
        limit: 10,
        offset: (this.page - 1) * 10
      })
      console.log(res)
      if (res.data.result.songs) {
        this.searchList.push(...res.data.result.songs)
        this.loading = false
      } else {
        this.finished = true
      }
    }
  },

  components: {
    MusicItem
  }
}
</script>

<style scoped lang='less'>
.hotSearch {
  padding: 0 10px;
}
.hotTags {
  font-size: 14px;
  color: #333;
}
span {
  display: inline-block;
  border: 1px solid red;
  font-size: 12px;
  padding: 5px 8px;
  border-radius: 15px;
  margin: 3px 5px 5px 0;
}
.searchRes {
  font-size: 14px;
}
.matching {
  color: #999;
  padding: 0 10px;
}
</style>
